import os

from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from dotenv import load_dotenv

load_dotenv('env.ini', encoding='utf-8')


class SMS(object):
    """
    短信类
    """
    def __init__(self):
        pass

    @staticmethod
    def create_client(access_key_id, access_key_secret):
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 您的 AccessKey ID,
            access_key_id=access_key_id,
            # 您的 AccessKey Secret,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = os.getenv('SMS_URL')
        return Dysmsapi20170525Client(config)

    @staticmethod
    def send(phone, code):
        client = SMS.create_client(os.getenv('SMS_ACCESS_KEY_ID'), os.getenv('SMS_ACCESS_KEY_SECRET'))
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=os.getenv('SMS_SIGN_NAME'),
            template_code=os.getenv('SMS_TEMPLATE_CODE'),
            phone_numbers=phone,
            template_param='{"code":"' + code + '"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            res = client.send_sms_with_options(send_sms_request, runtime)
            res = res.body.to_map()
            if res.get('Code') != 'OK':
                return {'status': -1, 'msg': res.get('Message')}
            return {'status': 0}
        except Exception as error:
            # 返回错误信息
            return {'status': -1, 'msg': UtilClient.assert_as_string(error.message)}

    @staticmethod
    async def main_async(phone, code):
        client = SMS.create_client(os.getenv('SMS_ACCESS_KEY_ID'), os.getenv('SMS_ACCESS_KEY_SECRET'))
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=os.getenv('SMS_SIGN_NAME'),
            template_code=os.getenv('SMS_TEMPLATE_CODE'),
            phone_numbers=phone,
            template_param='{"code":"' + code + '"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            await client.send_sms_with_options_async(send_sms_request, runtime)
            return True
        except Exception as error:
            # 如有需要，请打印 error
            UtilClient.assert_as_string(error.message)
            return False
